﻿using System;
using System.IO;
using EmbeddedSharp.Core;
using Zove.Runtime.Core;
using Zove.Runtime.Core.Zoom;

namespace Zove.Scripting.Core.Functions {
    /// <summary>
    /// Validate a model is alright.
    /// </summary>
    [Function("validate", "Validate a model is alright", "v=validate(\"circle\");", "v==true")]
    public class ValidateNode : ZoveScriptingContextFuncNode {

        /// <summary>
        /// Default constructor
        /// </summary>
        public ValidateNode()
            : base("validate") {
        }

        public override object Evaluate() {
            if (Parameters.Count == 0) {
                throw new ArgumentException(
                    "Usage: validate(modelAbosultePath)");
            }

            if (!(Parameters[0] is StringNode)) {
                throw new ArgumentException(
                    "The argument should be a string.");
            }

            try
            {
                ZoomLanguageNature languageNature = new ZoomLanguageNature();
                IRuntimeModelLoader loader = languageNature.ModelLoader;
                string modelName =
                    Convert.ToString(Parameters[0].Evaluate());
                if (File.Exists(modelName)) {
                    RuntimeModel rm = loader.LoadBySource(modelName);
                    rm.ToString();
                } else {
                    RuntimeModel rm = loader.LoadByClassName(modelName);
                    rm.ToString();
                }
            } catch (Exception ex) {
                Utils.Log(ex.Message);

                return false;
            }

            return true;
        }
    }
}
